import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
/**
 * @program: cdp-data-collector
 * @description: 对接coze生成token
 * @author: limeng
 * @create: 2025-01-14 10:17
 **/


public class CozeTokenClient {
    public static void main(String[] args) {
        String apiUrl = "https://api.coze.cn/api/permission/oauth2/token";
        String authorizationToken = "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IkVjY182emlYOGd1WGFiRElwa2xST1NBMDdnQUZEMmJkRVpndEtEQUdBRncifQ.eyJpc3MiOiIxMTk0NjczMjU5NjY3IiwiYXVkIjoiYXBpLmNvemUuY24iLCJpYXQiOjE3MzY5MjY3MTUsImV4cCI6MTczNjkzMDMxNSwianRpIjoiMWE3ZTZlMmRiZmQ2NGQ1MTlkMjljYTJmODliN2NlOTkiLCJzZXNzaW9uX25hbWUiOiJsaXNpIn0.ThjRjf6krtr-zbUgWP59LL0u-wfzyn1ZKSwq8mWnW4hdozMUk7tjfPxz8UXe6nIV34J2tu-QAY8BqVZus5FpiiCd0kY-ScVUbppcAJLPZD1YxyEpZKQuSyyl-uMgSupC36FZYu726q2a8WCJBB-FG-6bl-bxEIDJM7E64qNRYsFD8AvmNoF_0T-v77b5U2y3_U-SydP7hEBiUi2Qzg387u-tcchgQ_j-6PNNYtbhYaB_NhC6UwQe7onUoECVmmqbHy1RFce---MHj3bTqYbJk8f7d6iQPoqb6VlGqXkJEvdiYfAFCxK2-V3CXHa2S38qUILIp0ozvKBJpTtA6MsYPQ";
        JSONObject requestBody = new JSONObject();
        requestBody.put("duration_seconds", 86399);
        requestBody.put("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");

        try {
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(apiUrl);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", authorizationToken);
            httpPost.setEntity(new StringEntity(requestBody.toString()));

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String responseString = EntityUtils.toString(entity);
                JSONObject jsonResponse = JSON.parseObject(responseString);
                String accessToken = jsonResponse.getString("access_token");
                int expiresIn = jsonResponse.getIntValue("expires_in");
                System.out.println("Access Token: " + accessToken);
                System.out.println("Expires In: " + expiresIn);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
